//
//  CCKitManger.m
//  Haier
//
//  Created by aiquantong on 19/07/2017.
//  Copyright © 2017 aiquantong. All rights reserved.
//

#import "CCKitManger.h"

#import <KandySDK/KandySDK.h>

#import "BasicNavViewController.h"
#import "SessionMangementManager.h"
#import "ProvisionManager.h"
#import "HUDUtils.h"
#import "URICode.h"

#import "CCMPVRoomListViewController.h"
#import "LoginViewController.h"
#import "SupportViewController.h"
#import "CCCallViewController.h"

#import "UIAlertUtil.h"
#import "CCCallWindow.h"

@interface CCKitManger()
{
    NSURLSessionDataTask *task1;
    NSURLSessionDataTask *task2;
}

@end

@implementation CCKitManger


static CCKitManger *shareInstance = nil;

+(CCKitManger *)shareInstance
{
    static dispatch_once_t one;
    dispatch_once(&one, ^{
        if (shareInstance == nil) {
            shareInstance = [[CCKitManger alloc] init];
        }
    });
    return shareInstance;
}

#pragma mark viewController

-(void)showKandyDefaultVCWithPresentViewController:(UIViewController *)parentViewController;
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        KandySession *sk = [SessionMangementManager getSavedSessionData];
        if (sk && sk.currentUser) {
            [HUDUtils showHUDOnWindowWithText:@"正在登录.."];
            [CCKitManger loginKandyWithUserName:sk.currentUser.userId password:sk.currentUser.password callback:^(NSError *error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [HUDUtils hideHUDForWindow];
                    UIViewController *vc = nil;
                    if (error) {
                        vc = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
                    }else{
                        vc = [[SupportViewController alloc] initWithNibName:@"SupportViewController" bundle:nil];
                    }
                    
                    BasicNavViewController *navVC = [[BasicNavViewController alloc] initWithRootViewController:vc];
                    [parentViewController presentViewController:navVC
                                                       animated:NO
                                                     completion:^{
                                                         
                                                     }];
                });
            }];
        }else{
            LoginViewController *login = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
            BasicNavViewController *navVC = [[BasicNavViewController alloc] initWithRootViewController:login];
            [parentViewController presentViewController:navVC
                                               animated:NO
                                             completion:^{
                                                 
                                             }];
            
        }
    });
}


-(void)showKandyCallViewController:(BOOL)isPstn isVideo:(BOOL)isVideo callee:(NSString *)callee parentViewController:(UIViewController *)parentViewController
{
    [CCKitManger
     callWithIsPstn:isPstn
     isWithVideo:isVideo
     callee:callee
     callback:^(NSError *error) {
         dispatch_async(dispatch_get_main_queue(), ^{
             if (!error) {
                 CCCallViewController *cccall = [[CCCallViewController alloc] initWithNibName:@"CCCallViewController" bundle:nil];
                 [[CCCallWindow shareInstance] showInWindowWtihViewController:cccall];
             }else{
                 [UIAlertUtil showAlertWithTitle:@"提示" message:[error description] persentViewController:parentViewController];
             }
         });
     }];
}

-(void)showKandyMPVWithParentViewController:(UIViewController *)parentViewController;
{
    CCMPVRoomListViewController *cccall = [[CCMPVRoomListViewController alloc] initWithNibName:@"CCMPVRoomListViewController" bundle:nil];
    BasicNavViewController *navVC = [[BasicNavViewController alloc] initWithRootViewController:cccall];
    [parentViewController presentViewController:navVC animated:YES completion:nil];
}


#pragma mark setting

+(void)setCameraVideoResolution:(NSString *)cameraVideoResolution;
{
    [CallManager shareInstance].cameraVideoResolution = cameraVideoResolution;
}


+(void)setEnableLog:(BOOL)isConsoleLog fileLog:(BOOL)isFileLog;
{
    [KandyAdpter setEnableLog:isConsoleLog fileLog:isFileLog];
}



//注册kandy
+(void)registerWithKey:(NSString *)key secret:(NSString *)secret;
{
    [[KandyAdpter shareInstance] initKandySDKWithKey:key secret:secret];
}


#pragma mark account

-(void)requestDomainAccessToken:(void(^)(NSError *, NSString *))callback
{
    NSString *domainRequestUrlStr = [NSString stringWithFormat:@"%@/v1.3/domains/accessTokens?key=%@&domain_api_secret=%@",Kandy_Host_Url,[KandyAdpter shareInstance].apiKey,[KandyAdpter shareInstance].apiSecert];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:domainRequestUrlStr]];
    task1 = [[NSURLSession sharedSession]
             dataTaskWithRequest:request
             completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                 KDALog(@"requestDomainAccessToken data == %@  error == %@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding], [error description]);
                 NSError *newError = error;
                 if (!newError) {
                     NSError *jsonError = nil;
                     NSDictionary *objdic = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
                     if (!jsonError && [objdic isKindOfClass:[NSDictionary class]]) {
                         NSDictionary *result = [objdic objectForKey:@"result"];
                         if (result && [result isKindOfClass:[NSDictionary class]]) {
                             NSString *domain_access_token = result[@"domain_access_token"];
                             if (callback) {
                                 callback(nil, domain_access_token);
                             }
                             return;
                         }else{
                             newError= [[NSError alloc] initWithDomain:objdic[@"message"] code:0 userInfo:nil];
                         }
                     }else{
                         newError= [[NSError alloc] initWithDomain:@"Not Json Format" code:0 userInfo:nil];
                     }
                     
                 }
                 if (callback) {
                     callback(newError, nil);
                 }
             }];
    [task1 resume];

}

-(void)registerNewUserWithUserId:(NSString *)userid
                            mail:(NSString *)mail
                        password:(NSString *)pwd
                        callback:(void(^)(NSError *, NSDictionary *))callback;
{
    [self requestDomainAccessToken:^(NSError *error, NSString * domainAccessToken) {
        if (!error && domainAccessToken && [domainAccessToken length] > 0) {
            NSString *requestRequestUrlStr = [NSString stringWithFormat:@"%@/v1.3/domains/users/user_id?key=%@",Kandy_Host_Url, domainAccessToken];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestRequestUrlStr]];
            
            [request setHTTPMethod:@"POST"];
            NSString *bodyStr = [NSString stringWithFormat:@"user_id=%@&user_email=%@&user_password=%@",[URICode escapeUTF8URIComponent:userid],[URICode escapeUTF8URIComponent:mail],[URICode escapeUTF8URIComponent:pwd]];
            KDALog(@"registerNewUserWithUserId body == %@", bodyStr);

            [request setHTTPBody:[bodyStr dataUsingEncoding:NSUTF8StringEncoding]];
            
            task2 = [[NSURLSession sharedSession]
                     dataTaskWithRequest:request
                     completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                         KDALog(@"registerNewUserWithUserId  data == %@  error == %@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding], [error description]);
                         NSError *newError = error;
                         if (!newError) {
                             NSError *jsonError = nil;
                             NSDictionary *objdic = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
                             if (!jsonError && [objdic isKindOfClass:[NSDictionary class]]) {
                                 NSDictionary *result = [objdic objectForKey:@"result"];
                                 if (result && [result isKindOfClass:[NSDictionary class]]) {
                                     if (callback) {
                                         callback(nil, result);
                                     }
                                     return;
                                 }else{
                                     newError= [[NSError alloc] initWithDomain:objdic[@"message"] code:0 userInfo:nil];
                                 }
                             }else{
                                 newError= [[NSError alloc] initWithDomain:@"Not Json Format" code:0 userInfo:nil];
                             }
                         }
                         if (callback) {
                             callback(newError, nil);
                         }
                     }];
            [task2 resume];
        }else{
            if (callback) {
                callback(error, nil);
            }
        }
        
    }];
}






+(void)requestCodeBySMSCN:(NSString *)phoneNumber callback:(KandyCallback)callback;
{
    [[ProvisionManager shareInstance] requestCodeBySMSCN:phoneNumber
                                               callback:^(NSError *error) {
                                                   if (callback) {
                                                       callback(error);
                                                   }
                                               }];
}


+(void)validate:(NSString *)txtOTP phoneNumber:(NSString *)phoneNumber callback:(KandyUserCallback)callback;
{
    [[ProvisionManager shareInstance] validate:txtOTP
                                  phoneNumber:phoneNumber
                                     callback:^(NSError *error, KandyUserInfo *userInfo) {
                                         if (callback) {
                                             callback(error,userInfo);
                                         }
                                     }];
}

//登陆kandy
+(void)loginKandyWithUserName:(NSString *)userName password:(NSString *)password callback:(KandyCallback)callback;
{
    [AccessManager loginRN:userName
     password:password
     callback:^(NSError *error) {
         if (callback) {
             callback(error);
         }
         if (!error && [CCKitManger shareInstance].customProfile &&
             [[CCKitManger shareInstance].customProfile respondsToSelector:@selector(customCurProfileCallback:)]) {
             [[CCKitManger shareInstance].customProfile customCurProfileCallback:^(CustomProfileModel *model) {
                 
             }];
         }
     }];
}


+(NSString *)getcurLoginUser;
{
    return [SessionMangementManager getcurLoginUser];
}


//登出kandy
+(void)loginoutCallback:(KandyCallback)callback;
{
    [ProvisionManager deactivate:^(NSError *error) {
         if (callback) {
             callback(error);
         }
     }];
}


#pragma mark call
//本sdk中采用CCCallViewController为call处理委托控制器并将细节逻辑进行包装
//拨打电话
+(void)callWithIsPstn:(BOOL)isPstn isWithVideo:(BOOL)isVideo callee:(NSString *)Callee callback:(KandyCallback)callback;
{
    [[CallManager shareInstance]
     callWithIsPstn:isPstn
     isWithVideo:isVideo
     Callee:Callee
     Callback:^(NSError *error) {
         if (callback) {
             callback(error);
         }
     }];
}


//接收来电
+(void)accept:(KandyCallback)callback;
{
    [[CallManager shareInstance] accept:^(NSError *error) {
        if (callback) {
            callback(error);
        }
    }];
}

//拒绝来电
+(void)reject:(KandyCallback)callback;
{
    [[CallManager shareInstance] reject:^(NSError *error) {
        if (callback) {
            callback(error);
        }
    }];
}

//挂断通话
+(void)hangup:(KandyCallback)callback;
{
    [[CallManager shareInstance] hangup:^(NSError *error) {
        if (callback) {
            callback(error);
        }
    }];
}

//打开和关闭mic
+(void)startAndShutMute:(KandyCallback)callback;
{
    [[CallManager shareInstance] startAndShutMute:^(NSError *error) {
        if (callback) {
            callback(error);
        }
    }];
}

//打开和关闭camera
+(void)startAndShutLocalView:(KandyCallback)callback;
{
    [[CallManager shareInstance] startAndShutLocalView:^(NSError *error) {
        if (callback) {
            callback(error);
        }
    }];
}


+(void)switchSpeakerAndReceiver:(KandyCallback)callback;
{
    [[CallManager shareInstance]
     changeAudioRoute:[[CallManager shareInstance] getCurrentCall].audioRoute == EKandyCallAudioRoute_speaker?EKandyCallAudioRoute_receiver:EKandyCallAudioRoute_speaker
     Callback:^(NSError *error) {
         if (callback) {
             callback(error);
         }
     }];
}


+(void)switchFontAndBackCamera:(KandyCallback)callback;
{
    [[CallManager shareInstance] switchFBCamera:^(NSError *error) {
        if (callback) {
            callback(error);
        }
    }];
}


#pragma mark MPV
+(void)createRoomAndInvite:(NSArray *)inviteeArr callback:(KandyCallback)callback;
{
    [[ConferenceManager shareInstance]
     createRoomAndInvite:inviteeArr
     callback:^(NSError *error) {
         if (callback) {
             callback(error);
         }
    }];
}


+(void)inviteWithInviteeArr:(NSArray *)inviteeArr callback:(KandyCallback)callback;
{
    [[ConferenceManager shareInstance]
     inviteWithInviteeArr:inviteeArr
     callback:^(NSError *error) {
         if (callback) {
             callback(error);
         }
     }];
}

+(void)conferenceAccept:(KandyCallback)callback;
{
    [[ConferenceManager shareInstance] acceptConference:^(NSError *error) {
        if (callback) {
            callback(error);
        }
    }];
}

+(void)conferenceReject:(KandyCallback)callback;
{
    [[CallManager shareInstance] reject:^(NSError *error) {
        if (callback) {
            callback(error);
        }
    }];
    
    [[ConferenceManager shareInstance] leave:^(NSError *error) {

    }];
    
}

+(void)conferenceHangup:(KandyCallback)callback;
{
    [[CallManager shareInstance] hangup:^(NSError *error) {
        if (callback) {
            callback(error);
        }
    }];
    
    [[ConferenceManager shareInstance] leave:^(NSError *error) {

    }];
}


@end



